package com.jihox.abookpro.fragment;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.jihox.abookpro.GallerySelectActivity;
import com.jihox.abookpro.HomeChangeActivity;
import com.jihox.abookpro.MyApplication;
import com.jihox.abookpro.R;
import com.jihox.abookpro.ShowImageActivity;
import com.jihox.abookpro.dao.BookProductDAO;
import com.jihox.abookpro.domain.BookProduct;
import com.jihox.abookpro.util.ConfigProperties;
import com.jihox.abookpro.util.FileUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

public class HomeFragment extends Fragment {
	
//	private ProgressBar  web_progress;
//	private WebView web_product_info;
//	private Button back_btn;
//	private String scan_url = "";
	private String productNumber;
	private String templateName;
	private String productName;
	public String currentUrl;
	
	public BookProduct bookProduct;
//	private Vector<BookProduct> products = null;


	
//	private EditText dow_url;
//	private Button download;
	// 下载对话框
	private Dialog downloadDialog;
	// 进度条
	private ProgressBar mProgress;
	// 显示下载数值
	private TextView mProgressText;
	// 终止标记
	private boolean interceptFlag;
	private HttpHandler httpHandler;

	private ProgressDialog progress;
	
	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
				case 1:
					progress.dismiss();
					Toast.makeText(getActivity(), "模板安装成功", Toast.LENGTH_SHORT).show();
					goToGallerySelect();
				break;
			}
		}	
		
	};
	
//	private static final String SHAREDPREFERENCES_CUSTOMERINFO = "CUSTOMER_TOKEN";
	private ProgressBar pb;
	private WebView wv_home;
	private String cstToken;
	private String user_id_code;
	private HomeChangeActivity hca;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.activity_home_fragment, container,
				false);
		return view;
	}

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		pb = (ProgressBar) getActivity().findViewById(R.id.web_progress);
		wv_home = (WebView) getActivity().findViewById(R.id.wv_home);
		wv_home.getSettings().setLoadWithOverviewMode(true);
		wv_home.getSettings().setUseWideViewPort(true);
		wv_home.getSettings().setJavaScriptEnabled(true);
		//wv_home.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
	
//		//当前网络连接
//		ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
//		
//		NetworkInfo ni = cm.getActiveNetworkInfo();
//		if(ni!=null){
//			String url = getUrl(getLocalTemplates());
//			wv_home.loadUrl(url);
//		}else{
//			wv_home.loadUrl("file:///android_asset/staticWeb/template_list_empty.html");
//		}
		
		wv_home.setWebChromeClient(new WebChromeClient(){

			@Override
			public void onProgressChanged(WebView view, int newProgress) {

				if (newProgress == 100) {
					pb.setVisibility(View.GONE);
	              } else {
	                  if (View.GONE == pb.getVisibility()) {
	                	  pb.setVisibility(View.VISIBLE);
	                  }
	                  pb.setProgress(newProgress);
	              }
				super.onProgressChanged(view, newProgress);
			}
		});
		
		
		wv_home.setWebViewClient(new WebViewClient(){
			
			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				Log.w("msg_webview", errorCode+"---"+description+"---"+failingUrl);
				view.loadUrl("file:///android_asset/staticWeb/template_list_empty.html");
				// TODO Auto-generated method stub
				super.onReceivedError(view, errorCode, description, failingUrl);
			}
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, final String url) {
				String url_postfix = url.substring(url.lastIndexOf(".")+1);
				if(url_postfix.equals("zip")){
					final String template_name = url.substring(url.lastIndexOf("/")+1, url.lastIndexOf("."));//截取url获得模板名称
					templateName = template_name;
					Log.d("模板名", templateName);
					String[] number = template_name.split("_");
					productNumber = number[1];//模板编号，确认产品（日历2，照片书1,照片冲印3）
					productName = number[0] + "_" + number[1];
					String tp_name = number[0] + "_" + number[1]+"_"+number[2];
					String version_number = number[3];
					Log.d("产品名", productName);
					Log.d("msg_template_name", template_name);
					
					//查询本地是否已经下载过该模板
					boolean havetoload = true;
					final String path = Environment.getExternalStorageDirectory()+ ConfigProperties.getTemplatePath() + template_name;
//					File template_file = new File(path+"/"+template_name + ".xml");
					File template_file = new File(Environment.getExternalStorageDirectory()+ ConfigProperties.getTemplatePath());
					String[] template_files =  template_file.list();
					if(template_files != null){//判断模板目录是否为空
						for(int i = 0;i<template_files.length;i++){//循环判断模板是否损坏或者需要更新
							Log.i("msg_tempfile", template_files[i]);
							String[] old_number = template_files[i].split("_");
							String old_tp_name = old_number[0] + "_" + old_number[1]+"_"+old_number[2];
							String old_version_number = old_number[3];
							Log.i("msg_tp_name", tp_name+"_____________"+old_tp_name);						
							if(tp_name.equals(old_tp_name) ){//判断是否存在相同模板
								String mfilepath = Environment.getExternalStorageDirectory()+ ConfigProperties.getTemplatePath()+template_files[i];
								File mfile = new File(mfilepath);
								if(mfile.isDirectory()){
									Log.i("msg_version_number",  version_number+"_____________"+old_version_number);
									if(version_number.equals(old_version_number)){//判断是否存在模板版本号是否相同，如果相同则查看模板文件是否有缺失，如果缺失则需要重新下载
										File[] templateFile = mfile.listFiles();
										int xml_count = 0;
										for(i = 0;i<templateFile.length;i++){
											Log.i("msg_file", templateFile[i].getName());
											if(!templateFile[i].isDirectory()){
												if(templateFile[i].getName().equals(productName+".xml") || templateFile[i].getName().equals(templateName+".xml")){
													xml_count++;
												}
											}
										}
										if(xml_count == 2){
											havetoload = false;
										}else{
											Toast.makeText(getActivity(), "模板文件损坏，即将为您重新下载", Toast.LENGTH_SHORT).show(); 
		//									FileUtil.DeleteFolder(mfilepath);
										}
									}else{//如果模板版本号不相同则删除旧的版本						
										boolean isdelete = FileUtil.DeleteFolder(Environment.getExternalStorageDirectory()+ ConfigProperties.getTemplatePath()+template_files[i]);
										Log.i("msg_isdeletefile", isdelete+"");
									}
									break;
								}else{
									break;
								}
							}
						}
					}
					if(!havetoload){
//						Toast.makeText(WebProductIntroductionActivity.this, "该模板已下载过", Toast.LENGTH_SHORT).show();
							goToGallerySelect();
					}else{//检查当前网络状态，下载模板
					    ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
				        NetworkInfo ni = cm.getActiveNetworkInfo();
				        if( ni != null && ni.isConnectedOrConnecting()){
				        	if(ni.getType() == ConnectivityManager.TYPE_WIFI){//当前网络是否为WiFi状态
				        		downloadTemplate(url, path, template_name);//下载模板
				        	}else{
				        		//提示对话框
				        		AlertDialog.Builder  builder = new AlertDialog.Builder(getActivity());
				        		builder.setTitle(R.string.T_Kindly_Reminder);
				        		builder.setMessage(R.string.T_Wifi);
				        		builder.setPositiveButton(R.string.T_Ok, new AlertDialog.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										downloadTemplate(url, path, template_name);//下载模板
										
									}
								});
				        		builder.setNegativeButton(R.string.T_Cancel, new AlertDialog.OnClickListener(){

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										
										dialog.cancel();
									}
				        			
				        		});
				        		builder.create();
				        	    builder.show();
				        	}
				        }else{
				        	Toast.makeText(getActivity(), "当前网络不可用，请稍后再试", Toast.LENGTH_LONG).show();
				        }
						
						
						
					}
				}else{
					hca.fragmentindex = 9;
					hca.logoutButton.setBackgroundResource(R.drawable.return_btn_selector);
					hca.rgLine.setVisibility(View.GONE);
					hca.bottomRG.setVisibility(View.GONE);
					hca.titleText.setVisibility(View.GONE);
					currentUrl = url;
					wv_home.loadUrl(url);	
				}
//				Log.d("首页跳转Url", url);
//				Intent intent = new Intent(getActivity(), WebProductIntroductionActivity.class);
//				intent.putExtra("scan_result", url);
//				getActivity().startActivity(intent);
				return true;
			}
		});
		
		
		
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		cstToken = MyApplication.getInstance().getCstToken();
		user_id_code = MyApplication.getInstance().getUserId();
		loadMyUrl();
		super.onResume();
	}
	
	public void loadMyUrl(){
		//当前网络连接
		ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
		
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if(ni!=null){
			hca = (HomeChangeActivity) getActivity();
			String url;
			url = hca.myurl;
			if(url == null || url.equals("")){
				if(currentUrl == null || currentUrl.equals("")){
					url = getUrl(getLocalTemplates());
				}else{
					url = currentUrl;
				}
			}
			wv_home.loadUrl(url);
		}else{
			wv_home.loadUrl("file:///android_asset/staticWeb/template_list_empty.html");
		}
	}
	
	private List<String> getLocalTemplates(){
		List<String> localTemplates = new ArrayList<String>();
		File file = new File(Environment.getExternalStorageDirectory()+ConfigProperties.getTemplatePath());
		if(file.exists()){
			Log.i("msg_file", "文件存在");
			File[] files = file.listFiles();
			for (File file2 : files) {
				if (file2.isDirectory()) {
					Pattern p = Pattern.compile("\\d+_\\d+_\\d+_\\d+");
	                Matcher m = p.matcher(file2.getName());
	                if (m.matches()) {
	                	Log.d("文件名", file2.getName() + "");
	                	localTemplates.add(file2.getName());
					}
				}
			}
			
		}else{
			Log.i("msg_file", "文件不存在");
		}
		return localTemplates;
	}
	
	private String getUrl(List<String> localTemplates){
		//http://192.168.0.244:8080/PBMS2/app/templates?templates[0].id=12&templates[0].version=0templates[1].id=12&templates[1].version=0
		String url = ConfigProperties.getTemplateUrl();
		for (int i = 0; i < localTemplates.size(); i++) {
			String[] numbers = localTemplates.get(i).split("_");
			String id = numbers[2];
			String version = numbers[3];
			url = url + "templates[" + i + "].id=" + id + "&templates[" + i +"].version=" + version + "&";
		}
		
		if(localTemplates.size()!=0){			
			url = url.substring(0, url.lastIndexOf("&"));
		}
		if(!cstToken.equals("") && !user_id_code.equals("")){		
			url = url+"&cstToken="+URLEncoder.encode(cstToken);
		}
		TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(getActivity().TELEPHONY_SERVICE);
    	String imei = tm.getDeviceId();
    	url = url+"&deviceId="+imei;
		Log.i("msg", url);
		return url;
	}
	

	/**
	 * 下载模板
	 */
	private void downloadTemplate(String url,final String dlpath,final String dltemplate_name){
		HttpUtils http = new HttpUtils();
		Log.i("msg", "--------------------"+dlpath);
		httpHandler = http.download(url,dlpath+"/"+dltemplate_name+".zip",new RequestCallBack<File>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// TODO Auto-generated method stub
				
				Log.i("msg", "--------------------fail"+arg0+arg1);
			}

			@Override
			public void onLoading(long total, long current,
					boolean isUploading) {
				 //textView.setText("下载进度："+current+"/"+count);
				Log.i("msg", "--------------------"+total+"----------"+current);
				int progress = (int) (((double)current / total) * 100);
				Log.i("msg", "--------------------"+progress);
				mProgress.setProgress(progress);
				
				mProgressText.setText(current/1024+"kb" + "/" + total/1024+"kb");
				
			}

			@Override
			public void onStart() {
				showDownloadDialog();
			}

			@Override
			public void onSuccess(ResponseInfo<File> arg0) {
				// TODO Auto-generated method stub
//				Toast.makeText(MainActivity.this, "模板下载成功", Toast.LENGTH_SHORT).show();
				progress = new ProgressDialog(getActivity());
				progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				progress.setMessage("正在安装模板，请稍后...");
				progress.show();
				Log.i("msg", "--------------------success");
				httpHandler.cancel();
				try {		
					downloadDialog.dismiss();
					upZipFile(dlpath+"/"+dltemplate_name+".zip", dlpath);
				} catch (IOException e) {
					e.printStackTrace();
					Toast.makeText(getActivity(), "模板安装失败", Toast.LENGTH_SHORT).show();
				}
			}
			
		});
	}
	
	
	/**
	 * 显示下载对话框
	 */
	private void showDownloadDialog() {

		downloadDialog = new Dialog(getActivity(), R.style.JHDialog);
		// 设置它的ContentView
		downloadDialog.setContentView(R.layout.dialog_download);
		Button buttonCancel = (Button) downloadDialog
				.findViewById(R.id.dialog_button_cancel);
		mProgress = (ProgressBar) downloadDialog
				.findViewById(R.id.update_progress);
		mProgressText = (TextView) downloadDialog
				.findViewById(R.id.update_progress_text);
		TextView dialogTitle = (TextView) downloadDialog
				.findViewById(R.id.dialog_title);
		buttonCancel.setBackgroundResource(R.drawable.grey_style);
		buttonCancel.setText("取消");
		dialogTitle.setText("正在下载");

		buttonCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				downloadDialog.dismiss();
				interceptFlag = true;
				httpHandler.cancel();
			}
			
		});

		downloadDialog.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface arg0, int keyCode,
					KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					downloadDialog.dismiss();
					interceptFlag = true;
					httpHandler.cancel();
					return true;
				}
				return false;
			}
		});

		downloadDialog.setCanceledOnTouchOutside(false);
		downloadDialog.show();
	}
	
	/**
	 * 解压zip
	 * @throws IOException 
	 */
	private void upZipFile(String archive,String decompressDir) throws IOException{
		BufferedInputStream bi;
		ZipFile zf = new ZipFile(archive, "GBK");
		Enumeration e = zf.getEntries();
		while(e.hasMoreElements()){
			ZipEntry ze2 = (ZipEntry) e.nextElement();
			String entryName = ze2.getName();
			String path = decompressDir +"/"+entryName;
			if(ze2.isDirectory()){//判断当前读取的是否是目录
				Log.i("msg", "正在创建解压目录"+entryName);
				File decompressDirFile = new File(path);
				if(!decompressDirFile.exists()){
					decompressDirFile.mkdirs();
				}
				
//				String dir = entryName.substring(0, entryName.indexOf("/"));
//				Log.d("目录", dir + "");
//				//判断material？background
//				if ("material".equals(dir)) {
//					//资源
//				}else if ("background".equals(dir)) {
//					//background
//					String name = entryName.substring(entryName.indexOf("/") + 1);
//					Log.d("Name", name + "");
//					Bitmap picture = BitmapFactory.decodeStream(zf.getInputStream(ze2));
//					Background background = new Background();
//					BackgroundDAO backgroundDAO = new BackgroundDAO(WebProductIntroductionActivity.this);
//					background.setName(name);
//					background.setPicture(picture);
//					Log.d("背景图片名", background.getName() + "");
//					backgroundDAO.addBackground(background);				
//				}
			}else{//解压出的是文件
				Log.i("msg", "正在创建解压文件"+entryName);
				String fileDir = path.substring(0, path.lastIndexOf("/"));
				File fileDirFile = new File(fileDir);
				if(!fileDirFile.exists()){
					fileDirFile.mkdirs();
				}
				BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(decompressDir+"/"+entryName));
				bi = new BufferedInputStream(zf.getInputStream(ze2));
				//将BookTemplate写入DB
//				BookTemplate bookTemplate = new BookTemplate();
//				BookTemplateDAO bookTemplateDAO = new BookTemplateDAO(WebProductIntroductionActivity.this);
//				try {
//					bookTemplate = bookTemplateDAO.retrieveBookTemplate(zf.getInputStream(ze2));
//					Log.d("Tid", bookTemplate.getTid() + "");
//				} catch (Exception e1) {
//					e1.printStackTrace();
//				}
//				bookTemplateDAO.addBookTemplate(bookTemplate);
				
				byte[] readContent = new byte[1024];
				int readCount = bi.read(readContent);
				while(readCount!=-1){
					bos.write(readContent,0, readCount);
					readCount = bi.read(readContent);
					
				}
				bos.close();
				
			}
		}
		zf.close();
		Message msg = handler.obtainMessage();
		msg.what = 1;
		handler.sendMessageDelayed(msg, 1500);
		//模板解压成功，删除下载的压缩文件包
		File file = new File(archive); 
		file.delete();
	}

	private void goToGallerySelect() {

		if (ShowImageActivity.selectedPhotoList != null) {
			ShowImageActivity.selectedPhotoList.clear();
		}		
		ShowImageActivity.showNextButton = false;
//			bookProduct = products.get(0);
		//从SD卡中读取Product
		BookProductDAO dao = new BookProductDAO(getActivity());
		try {
			//从SD卡中读取Product
			File file = new File(Environment.getExternalStorageDirectory(), ConfigProperties.getTemplatePath() +
	                 templateName + "/" +
	                 productName +
	                 ".xml");
			if (Environment.getExternalStorageState().equals(
	                Environment.MEDIA_MOUNTED)) {
				try {
					FileInputStream inputStream = new FileInputStream(file);
					bookProduct = dao.retrieveProduct(inputStream);
					Log.d("Product File", file.getName());
				} catch (Exception e) {
					Toast.makeText(getActivity(), getResources().getString(R.string.T_Read_Template_Error),
	                     Toast.LENGTH_SHORT).show();
				}
	         }else {
	         // 此时SDcard不存在或者不能进行读写操作的
	         Toast.makeText(getActivity(),
	                 getResources().getString(R.string.T_No_SDCard), Toast.LENGTH_SHORT).show();
			 }
		} catch (Exception e) {
			e.printStackTrace();
		}
		MyApplication.getInstance().setTemplate(null);//清空全局变量中的booktemplate
		Intent intent = new Intent();
		intent.putExtra("templateName", templateName);
		intent.putExtra("bookProduct", bookProduct);
		intent.setClass(getActivity(),GallerySelectActivity.class);
		startActivity(intent);
	}
	
}
